// ============================== 导入依赖 ============================== //

import CORE from '@login/CORE'
import TRANS from '@demo/CORE/UTIL/init/TRANS'

import Client from '@api/user/api/SysUserApi'

import OneClass from '@api/user/model/SysUserDto'

const CLIENT = CORE.grpcCLIENT(Client)

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 单项 —————————————————————————————— //

  async getUser(name = '用户') {
    if (sessionStorage.USER) return JSON.parse(sessionStorage.USER)

    const DTO = CORE.grpcDTO(OneClass)
    const resp = await CORE.grpc(TRANS.transTip(name), CLIENT, 'getUser', DTO)

    const USER = {
      ...resp.sysUserDto,

      isAdmin: resp.isSuperAdmin,
      menuTree: transMenu(resp.sysMenuDto),

      roleId: resp.sysRoleDto.map(({ id }) => id),
      roleList: resp.sysRoleDto,

      organId: resp.sysOrganDto.map(({ id }) => id),
      organList: resp.sysOrganDto,

      regionId: resp.sysRegionDto.map(({ id }) => id),
      regionList: resp.sysRegionDto,
    }

    sessionStorage.USER = JSON.stringify(USER)

    return USER
  },
}

// ============================== 转换方法 ============================== //

const transMenu = (tree) => {
  // 排序
  tree.sort((a, b) => a.sort - b.sort)

  tree.forEach((item) => {
    const children = item.children || []

    // 先递归所有子节点
    transMenu(children)

    // 以 describe 存储该菜单下的第一个路由目录
    if (item.catalogue) item.describe = item.catalogue === 'none' ? item.id : item.catalogue
    else item.describe = (children[0] || {}).describe
  })

  return tree
}
